//
//  FRReadAdContentViewController.m
//  Fresh Reading
//
//  Created by Annie on 2020/5/25.
//  Copyright © 2020 Annie. All rights reserved.
//

#import "FRReadAdContentViewController.h"


@interface FRReadAdContentViewController ()<UITableViewDataSource, UITableViewDelegate, BUNativeExpressAdViewDelegate>

@property (nonatomic, strong) UITableView *fr_tableView;
@property (nonatomic, strong) FRLabel *fr_tip_label;
@property (nonatomic, strong) BUNativeExpressAdManager *adManager;
@property (nonatomic, strong) NSMutableArray *dataSource;

@property (nonatomic, strong) NSMutableArray<__kindof BUNativeExpressAdView *> *expressAdViews;


@end

@implementation FRReadAdContentViewController

- (void)dealloc {
    _fr_tableView.delegate = nil;
    _adManager.delegate = nil;
    _adManager = nil;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    FRReadBackgroundConfigModel *bgConfig = [FRReadConfigManager manager].configModel.fr_backgroundConfigModel;
    self.view.backgroundColor = [UIColor gg_colorWithHexString:bgConfig.fr_color_hex];
    
    
    
    
//    CGSize size = self.view.bounds.size;
    
//    size = CGSizeMake(size.width, 200);
    
    
    self.fr_tableView = [[UITableView alloc] initWithFrame:CGRectZero];
    [self.view addSubview:self.fr_tableView];
    
    [self.fr_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.height.mas_equalTo(300);
        make.centerY.mas_equalTo(self.view).offset(-100);
    }];
    
    
    self.fr_tableView.delegate = self;
    self.fr_tableView.dataSource = self;
    self.fr_tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [self loadNativeAds];
    
    
    [self.view addSubview:self.fr_tip_label];
    [self.fr_tip_label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.fr_tableView);
        make.top.mas_equalTo(self.fr_tableView.mas_bottom).offset(60);
    }];
    
}

- (void)loadNativeAds {
    
    BUAdSlot *slot1 = [[BUAdSlot alloc] init];
    slot1.ID = [FRAdManager manager].pg_reading_native_config.fr_slotID_csj;
    slot1.AdType = BUAdSlotAdTypeFeed;

    slot1.position = BUAdSlotPositionFeed;
//    slot1.imgSize = [BUSize sizeBy:BUProposalSize_Banner600_90];
    slot1.imgSize = [BUSize sizeBy:BUProposalSize_Feed690_388];
//    slot1.imgSizeArray = @[[BUSize sizeBy:BUProposalSize_Banner600_90],[BUSize sizeBy:BUProposalSize_Feed690_388]];
    slot1.isSupportDeepLink = YES;
    
    CGSize size = self.view.bounds.size;
    
    BUNativeExpressAdManager *nad = [[BUNativeExpressAdManager alloc] initWithSlot:slot1 adSize:CGSizeMake(size.width - 0 * 2, 300)];


    nad.delegate = self;
    self.adManager = nad;
    
    [nad loadAd:3];
}

- (NSMutableArray *)dataSource{
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

- (NSMutableArray<__kindof BUNativeExpressAdView *> *)expressAdViews{
    if (!_expressAdViews) {
        _expressAdViews = [NSMutableArray array];
    }
    return _expressAdViews;
}

//- (void)nativeAdsManagerSuccessToLoad:(BUNativeAdsManager *)adsManager nativeAds:(NSArray<BUNativeAd *> *_Nullable)nativeAdDataArray


- (void)nativeExpressAdSuccessToLoad:(BUNativeExpressAdManager *)nativeExpressAd views:(NSArray<__kindof BUNativeExpressAdView *> *)views{
    NSLog(@"feed datas load success");

    if (views.count) {
        
        [views enumerateObjectsUsingBlock:^(__kindof BUNativeExpressAdView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [obj render];
        }];
        
        [self.expressAdViews removeAllObjects];
        [self.expressAdViews addObjectsFromArray:views];
    }
    
    
//    [self.view addSubview:self.expressAdViews.firstObject];
//    self.expressAdViews.firstObject.center = self.view.center;
//    
//    
//    return;
    [self.fr_tableView reloadData];
}
- (void)nativeExpressAdFailToLoad:(BUNativeExpressAdManager *)nativeExpressAd error:(NSError *_Nullable)error{
    
}


#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return MIN(1, self.expressAdViews.count);
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
//    cell = [tableView dequeueReusableCellWithIdentifier:@"BUDNativeExpressCell"];
   cell.selectionStyle = UITableViewCellSelectionStyleNone;
           
   // 重用BUNativeExpressAdView，先把之前的广告试图取下来，再添加上当前视图
   UIView *subView = (UIView *)[cell.contentView viewWithTag:1000];
   if ([subView superview]) {
       [subView removeFromSuperview];
   }
   
   UIView *view = [self.expressAdViews objectAtIndex:indexPath.row];
   view.tag = 1000;

   [cell.contentView addSubview:view];
    return cell;
}



#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    float HightFloat = 0;
        
    UIView *view = [self.expressAdViews objectAtIndex:arc4random()%self.expressAdViews.count];
    
    HightFloat =  view.bounds.size.height;
    
    
    [self.fr_tableView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(HightFloat);
    }];
    
    
    
    return HightFloat;
}


#pragma mark
- (void)nativeAd:(BUNativeAd *)nativeAd dislikeWithReason:(NSArray<BUDislikeWords *> *)filterWords {
    NSLog(@"click dislike");
    NSMutableArray *dataSources = [self.dataSource mutableCopy];
    [dataSources removeObject:nativeAd];
    self.dataSource = [dataSources copy];
    [self.fr_tableView reloadData];
}

- (void)videoAdView:(BUVideoAdView *)videoAdView stateDidChanged:(BUPlayerPlayState)playerState {
    NSLog(@"videoAdView state change to %ld", (long)playerState);
}

- (void)videoAdView:(BUVideoAdView *)videoAdView didLoadFailWithError:(NSError *)error {
    NSLog(@"videoAdView didLoadFailWithError");
}

- (void)playerDidPlayFinish:(BUVideoAdView *)videoAdView {
    NSLog(@"videoAdView didPlayFinish");
}




- (UITableView *)fr_tableView{
    if (!_fr_tableView) {
        UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.backgroundColor = [UIColor clearColor];
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        [tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"BUDNativeExpressCell"];
        
        _fr_tableView = tableView;
    }
    return _fr_tableView;
}


- (FRLabel *)fr_tip_label{
    if (!_fr_tip_label) {
        FRLabel *label = [FRLabel new];
        label.font = kFRFontRegular(14);
        
        
        label.textColor = [FRReadConfigManager manager].configModel.fr_textConfigModel.fr_color;
        
//        label.textColor = rgba(250, 250, 250, 1);
        label.textAlignment = NSTextAlignmentCenter;
        label.text = @"点击/滑动可继续阅读";
        _fr_tip_label = label;
    }
    return _fr_tip_label;
}


@end
